import React, { Component } from 'react'
import { Button, Divider, Input, Modal, Popconfirm, Select, Table } from 'antd'
import { findKey, map } from 'lodash'
import '../../less/index.less'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import ReactDragListView from 'react-drag-listview'
import SelectStatus from '../common/select-status-cell'
import * as action from '../../actions/assignment'
import { TwsReactMarkdownPreview } from 'tws-antd'
import { quizType } from '../../constant/constant-data'
import PreviewAssignment from '../assignemnt/preview-assignment'
import EditableCell from '../common/editable-cell'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../../constant/lang-util'

const Option = Select.Option

class TaskContent extends Component {
  constructor () {
    super()
    this.state = {
      expandIconAsCell: false,
      expandRowByClick: true,
      expandedRowKeys: [],
      taskId: -1,
      programId: -1,
      showQuizzesModel: false,
      visible: false,
      previewAssignment: {},
      ediableId: 0,
      editable: false,
      modalVisible: false,
      value: '',
      buttonProps: true,
      assignment: {}
    }
  }

  componentDidMount () {
    this.setState({
      taskId: this.props.match.params.taskId,
      programId: this.props.match.params.programId
    })
  }

  handleAdd () {
    this.setState({modalVisible: true})
  }

  handleOk () {
    const {taskId} = this.props.match.params
    const task = this.props.task
    const assignments = task.assignments
    const orderNumber = assignments.length === 0 ? 0 : assignments[assignments.length - 1].orderNumber + 1
    const {type, value} = this.state
    this.setState({
      modalVisible: false,
      taskId: taskId
    }, () => {
      const newAssignment = {
        taskId: taskId,
        type: type,
        title: value,
        orderNumber: orderNumber
      }
      this.props.addNewAssignment(taskId, newAssignment,
        () => this.props.getTask(taskId))
    })
  }

  handleCancel () {
    this.setState({modalVisible: false})
  }

  onCellChange (value, record, type) {
    if (value === undefined) {
      this.setState({editable: false})
      return
    }

    if (type === 'type') {
      record[type] = quizType[value]
    } else {
      record[type] = value
    }
    this.setState({type: quizType[value], editable: false}, () => {
      this.props.addAssignmentInfo(record)
    })
  }

  selectQuizzes (record) {
    this.props.history.push(`/program/${this.state.programId}/task/${this.props.task.id}/assignment/${record.id}?type=${record.type}`)
  }

  displayPreviewAssignment (assignment) {
    this.setState({visible: true, assignment: assignment})
  }

  previewAssignment (assignment) {
    const quizIds = assignment.selectedQuizzes.map(item => item.quizId)
    this.props.getSelectQuizzes(assignment.type, quizIds,
      () => this.displayPreviewAssignment(assignment))
  }

  closeModal () {
    this.setState({visible: false})
    this.props.clearSelectedQuizzes()
  }

  confirm (assignmentId) {
    const {task} = this.props
    this.props.deleteAssignment(assignmentId, task.id, () =>
      this.props.getTask(task.id))
  }

  handleChange (value) {
    this.setState({type: quizType[value], buttonProps: false})
  }

  handleVisible (assignment) {
    const {taskId} = this.props.match.params
    this.props.changeAssignmentVisible(taskId, assignment.id, !assignment.visible)
  }

  render () {
    const {expandRowByClick, expandIconAsCell, expandedRowKeys, visible, assignment} = this.state
    const {task, program} = this.props
    const {readOnly} = program
    const assignments = task.assignments

    const optionals = map(quizType, (value, key) => key).filter(item => item !== '编程题')
    const columns = [{
      title: <FormattedMessage id='作业类型' />,
      width: '20%',
      dataIndex: 'type',
      render: (text, record) => {
        const selectedQuizzes = record.selectedQuizzes ? record.selectedQuizzes : []
        const noConfirmClassName = record.id === this.state.ediableId && this.state.editable
          ? 'no-confirm' : ''

        return <SelectStatus operationIconClassName={noConfirmClassName}
          value={findKey(quizType, (value) => value === text)} id={record.id}
          onChange={value => this.onCellChange(value, record, 'type')}
          optionals={optionals}
          changEditable={(editable) => this.setState({editable, ediableId: record.id})}
          disable={selectedQuizzes.length > 0}
        />
      }
    }, {
      title: <FormattedMessage id='名称' />,
      dataIndex: 'title',
      width: '20%',
      render: (text, record) => {
        return (
          <EditableCell
            isReadOnly={readOnly}
            value={text}
            onChange={value => this.onCellChange(value, record, 'title')}
          />)
      }
    }, {
      title: <FormattedMessage id='已绑定题目ID' />,
      dataIndex: 'quizId',
      width: '20%',
      render: (text, record) => {
        return record.selectedQuizzes.map(item => item.quizId).toString()
      }
    }, {
      title: <FormattedMessage id='状态' />,
      dataIndex: 'visible',
      width: '10%',
      render: (text, record) => {
        return <span>{record.visible ? <FormattedMessage id='可见' /> : <FormattedMessage id='不可见' />}</span>
      }
    }, {
      title: <FormattedMessage id='操作' />,
      dataIndex: 'id',
      render: (text, record) => {
        const noConfirmClassName = record.id === this.state.ediableId && this.state.editable
          ? 'no-confirm' : ''
        const selectedQuizzes = record.selectedQuizzes ? record.selectedQuizzes : []
        if (readOnly) {
          return <a className={selectedQuizzes.length > 0 ? '' : 'hidden'}
            onClick={this.previewAssignment.bind(this, record)}><FormattedMessage id='预览' /></a>
        }
        return <span>
          {
            record.type !== 'HOMEWORK_QUIZ'
              ? <span>
                <a className={noConfirmClassName} onClick={this.selectQuizzes.bind(this, record)}><FormattedMessage
                  id='选题' /></a>
                <span className='ant-divider' />
              </span>
              : ''
          }
          <Popconfirm
            title='Are you sure delete this task?'
            onConfirm={this.confirm.bind(this, record.id)}
            okText='Yes'
            cancelText='No'>
            <a><FormattedMessage id='删除' /></a>
          </Popconfirm>
          <span className='ant-divider' />
          <a onClick={this.handleVisible.bind(this, record)}>{record.visible ? <FormattedMessage id='学员不可见' />
            : <FormattedMessage id='学员可见' />}</a>
          <span className={selectedQuizzes.length > 0 ? 'ant-divider' : 'hidden'} />
          <a className={selectedQuizzes.length > 0 ? '' : 'hidden'}
            onClick={this.previewAssignment.bind(this, record)}><FormattedMessage id='预览' /></a>
          <span className='ant-divider' />
          <a id='assignment' className='drag-handle'><FormattedMessage id='拖拽排序' /></a>
        </span>
      }
    }]
    const that = this
    const drag = {
      onDragEnd (fromIndex, toIndex) {
        const data = that.props.task.assignments
        const item = data.splice(fromIndex, 1)[0]
        data.splice(toIndex, 0, item)
        that.props.dragSort(data, that.props.task.id)
      },
      handleSelector: '#assignment'
    }
    return (
      <div>
        <h4 className='margin-t-3 margin-b-2'><FormattedMessage id='任务卡内容' /></h4>
        <div className='mark-down-wrap'>
          <TwsReactMarkdownPreview source={task.content} />
        </div>
        <div>
          <h4 className='margin-t-4 margin-b-2'><FormattedMessage id='作业' /></h4>
          <div>
            <Button type='primary' className='editable-add-btn'
              disabled={readOnly}
              onClick={this.handleAdd.bind(this, task.id)}><FormattedMessage id='新增题目类型' /></Button>
            <Divider type='vertical' />
            <Button
              onClick={() => { window.location.href = `./index.html#/program/${this.state.programId}` }}><FormattedMessage
                id='返回主题' /></Button>
            {
              readOnly
              ? ''
                : <div className='visible-btn'>
                  <a onClick={() => { this.props.changeAssignmentsVisible(task.id, true) }}><FormattedMessage
                    id='全部可见' /></a>
                  <Divider type='vertical' />
                  <a onClick={() => { this.props.changeAssignmentsVisible(task.id, false) }}><FormattedMessage id='全部不可见' /></a>
                </div>
            }

            <ReactDragListView {...drag}>
              <Table className='programList-table' bordered dataSource={assignments} columns={columns}
                expandRowByClick={expandRowByClick}
                expandIconAsCell={expandIconAsCell}
                expandedRowKeys={expandedRowKeys}
                rowKey={record => record.id}
              />
            </ReactDragListView>
          </div>
        </div>
        <PreviewAssignment visible={visible}
          assignment={assignment}
          taskId={task.id}
          closeModal={this.closeModal.bind(this)}
        />
        <Modal
          title={<FormattedMessage id='请填写作业信息' />}
          centered
          width={600}
          okText={<FormattedMessage id='确定' />} cancelText={<FormattedMessage id='取消' />}
          visible={this.state.modalVisible}
          onOk={this.handleOk.bind(this)}
          onCancel={this.handleCancel.bind(this)}
          okButtonProps={{disabled: this.state.buttonProps}}>
          <FormattedMessage id='作业类型' />：<Select onChange={this.handleChange.bind(this)} style={{width: 140}}
            placeholder={convertContent('作业类型')}>
            {
            optionals.map((optional, index) => {
              return <Option value={optional} key={index}>{convertContent(optional)}</Option>
            })
          }
          </Select>&nbsp;&nbsp;&nbsp;
          <FormattedMessage id='作业名称' />：<Input style={{width: 140}}
            onChange={e => this.setState({value: e.target.value})} />
        </Modal>

      </div>)
  }
}

const mapStateToProps = ({taskInfo, quizzes, program}) => ({
  assignments: taskInfo.assignments,
  selectedQuizzes: quizzes,
  program
})

const mapDispatchToProps = dispatch => ({
  addNewAssignment: (taskId, newAssignment, callback) => dispatch(action.addAssignment(taskId, newAssignment, callback)),
  addAssignmentInfo: (assignment) => dispatch(action.addAssignmentInfo(assignment)),
  deleteAssignment: (assignmentId, taskId, callback) => dispatch(action.deleteAssignment(assignmentId, taskId, callback)),
  getSelectQuizzes: (type, quizIds, callback) => dispatch(action.getQuizzesByIds(type, quizIds, callback)),
  dragSort: (data, taskId) => dispatch(action.dragSort(data, taskId)),
  clearSelectedQuizzes: () => dispatch({type: 'CLEAR_SELECTED_QUIZZES'}),
  changeAssignmentVisible: (taskId, assignmentId, visibility) => dispatch(action.changeAssignmentVisible(taskId, assignmentId, visibility)),
  changeAssignmentsVisible: (taskId, visibility) => dispatch(action.changeAssignmentsVisible(taskId, visibility))
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TaskContent))
